<template>
  <div class="_wrapper _rel com-vditor-box">
    <div :id="'com-vditor-' + randomId" class="_wrapper"></div>
  </div>
</template>
<script>
import Vditor from "vditor";
import "vditor/dist/index.css";
import ToolUpload from "@/components/com-upload/tool-upload.js";

let vditor;

export default {
  props: {
    content: {
      type: String,
      default: "欢迎使用!",
    },
  },
  data() {
    return {
      randomId: new Date().getTime(),
    };
  },
  mounted() {
    let _this = this;
    vditor = new Vditor("com-vditor-" + this.randomId, {
      toolbarConfig: {
        pin: true,
      },
      cache: {
        enable: false,
      },
      counter: {
        enable: true,
      },
      after: () => {
        vditor.setValue(_this.content);
      },
      upload: {
        multiple: true,
        // url: _this.$comStore.app.baseApi + "/public/storage/store",
        // fieldName: "file",
        // headers: {
        //   ntd_token: _this.$comStore.login.token,
        // },
        // extraData: {
        //   channelBusinessId: "402809817fbc4f3d017fbcbed26a001d",
        //   bucketName: "app-bucket",
        // },
        async handler(files) {
          let res = await ToolUpload.upload(files);
          res.forEach((item) => {
            vditor.insertValue(
              `![${item.fileKey}](${item.fileUrl
                .replaceAll(" ", "")
                .replaceAll("=", "")})`
            );
          });
        },
        // format(files, resContent) {
        //   let res = JSON.parse(resContent);
        //   return JSON.stringify({
        //     msg: "",
        //     code: 0,
        //     data: {
        //       errFiles: [],
        //       succMap: {
        //         fileName: res.data.fileUrl,
        //       },
        //     },
        //   });
        // },
      },
    });
    // 设置每秒同步更新
    setInterval(() => {
      this.$emit("update:content", this.getVal());
    }, 1000);
  },
  methods: {
    getVal() {
      return vditor.getValue();
    },
    toPreview() {
      var evt = document.createEvent("Event");
      evt.initEvent("click", true, true);
      vditor.vditor.toolbar.elements.preview.firstElementChild.dispatchEvent(
        evt
      );
    },
  },
};
</script>
<style>
.com-vditor-box ul li {
  list-style: circle;
}
.com-vditor-box ol li {
  list-style: auto;
}
</style>
